/* 
 * created by senllang 2024/1/4 
 * mail : study@senllang.onaliyun.com 
 *
 * Copyright (c) 2023-2024 senllang

 * This is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 * 
 */

/* 
 * 每个线程可以有自己信号掩码。
 * fork出来的子进程会继承父进程的信号掩码，exec后信号掩码保持不变。如果父进程是多线程，那么子进程只继承主线程的掩码。
 * 针对进程发送的信号，会被任意的没有屏蔽该信号的线程接收，注意只有一个线程会随机收到。linux下如果都可以所有线程都可以接收信号，那么信号将默认发送到主线程，posix系统是随机发送。
 * fork之后子进程里pending的信号集初始化为空，exec会保持pending信号集。
*/
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
  
typedef void (*sighandler_t)(int);
  
static void *thread1(void *arg)
{
    sigset_t set;
      
    printf("in thread1\n");
  
    sigemptyset(&set);
    sigaddset(&set, SIGTERM);
    pthread_sigmask(SIG_BLOCK, &set, NULL);

    while(1) {
        sleep(1);
    }
}
  
static void sigset_print(sigset_t *set)
{
    int i;
  
    for (i = 1; i <= SIGSYS; i++) {
        if (sigismember(set, i)) {
            printf("signal %d is in set\n",i);
        }
    }
}
  
int main(int argc, char **argv)
{
    int ret;
    sigset_t set;
    pthread_t pid;
  
    pthread_create(&pid, NULL, thread1, NULL);
    sleep(1);
  
    sigemptyset(&set);
    sigaddset(&set, SIGINT);
    pthread_sigmask(SIG_BLOCK, &set, NULL);
  
    ret = fork();
    if (ret == 0) {
        //child
        pthread_sigmask(SIG_BLOCK, NULL, &set);
        sigset_print(&set);
  
        while(1) {
            sleep(1);
        }
    }else if (ret > 0) {
        //parent
        while(1) {
            sleep(1);
        }
    }else{
        perror("");
        abort();
    }
  
}
